package com.sinosoft.hydra.um.services.component.dataimport.validators;


import com.sinosoft.hydra.um.services.component.dataimport.resolvers.ValidateResult;
import cn.com.sinux.spring.utils.ConvertUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2015/1/10.
 */
public abstract class Validator {

    /**
     * @param value
     * @return
     */
    public abstract ValidateResult validate(Object value);

    public static List<Validator> createValidatorKeys(String validatorKeys) {
        List<Validator> validators = new LinkedList<Validator>();
        Matcher matcher = Pattern.compile("([a-zA-Z]+)(?:\\[([^\\]]+)\\])?").matcher(validatorKeys);
        while (matcher.find()) {
            validators.add(createValidator(matcher.group(1), matcher.group(2)));
        }
        return validators;
    }

    private static Validator createValidator(String key, String value) {
        if ("enumNumber".equals(key)) {
            List<Integer> values = ConvertUtils.loadIntegerList(value, ',');
            Integer[] arrays = new Integer[value.length()];
            return new EnumNumberValidator(values.toArray(arrays));
        } else if ("enumString".equals(key)) {
            return new EnumStringValidator(value.split(","));
        } else if ("maxNumber".equals(key)) {
            return new MaxNumberValidator(Double.valueOf(value.trim()));
        } else if ("maxScale".equals(key)) {
            return new MaxScaleValidator(Integer.valueOf(value.trim()));
        } else if ("maxSize".equals(key)) {
            return new MaxSizeValidator(Integer.valueOf(value.trim()));
        } else if ("minNumber".equals(key)) {
            return new MinNumberValidator(Integer.valueOf(value.trim()));
        } else if ("minSize".equals(key)) {
            return new MinSizeValidator(Integer.valueOf(value.trim()));
        } else if ("notNull".equals(key)) {
            return new NotNullValidator();
        } else if ("regular".equals(key)) {
            return new RegularExpressionValidator(value.trim());
        } else if ("special".equals(key)) {
            return new SpecialCharactersValidator();
        } else {
            return null;
        }
    }
}
